package icursoft.educationms.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import icursoft.educationms.R;
import icursoft.educationms.ui.fragment.ProgressDialogFragment;

/**
 * Created by Administrator on 2016/12/20.
 */

public class CommUtil {
    public static final String TAG = "CommUtil";
    static int countm;
    static int counth;
    static String scounts;
    static String scountm;
    static String scounth;
    static String timecount;
    private static Toast mToast = null;
    /** dialog tag*/
    private static String mDialogTag = "dialog";

    public static String getCurrentTime() {
        return getCurrentTime("yyyy/MM/dd HH:mm:ss");
    }

    public static String getCurrentTime2() {
        return getCurrentTime("yyyy-MM-dd HH:mm:ss");
    }

    public static String getCurrentTime(String format) {
        return new SimpleDateFormat(format, Locale.getDefault())
                .format(new Date());
    }

    public static String getCurrentDate() {  //yyyy-MM-dd
        return getCurrentTime("yyyy-MM-dd");
    }

    public static String getSpecificDate(int diffrent) {  //yyyy-MM-dd 与当前日期的差
        Calendar c   =   Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH,diffrent);
        return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                .format(c.getTime());

    }
    /**
     * 将日历格式化为format格式的字符串
     * @param c
     * @param format
     * @return
     */
    public static String getDateFormat(Calendar c, String format){
        return new SimpleDateFormat(format).format(c.getTime());
    }

    public static void initTimer() {
        countm = 0;
        counth = 0;
    }

    public static String dealTimer(int counts) {

        if (counts < 60) {

        } else {
            counts = 0;
            countm++;
            if (countm < 60) {

            } else {
                countm = 0;
                counth++;
                if (counth < 24) {

                } else {
                    counth = 0;

                }
            }

        }

        if (counth < 10) {
            scounth = "0" + counth;
        } else {
            scounth = String.valueOf(counth);
        }
        if (countm < 10) {
            scountm = "0" + countm;
        } else {
            scountm = String.valueOf(countm);
        }
        if (counts < 10) {
            scounts = "0" + counts;
        } else {
            scounts = String.valueOf(counts);
        }
        timecount = scounth + ":" + scountm + ":" + scounts;
        return timecount;
    }

    /**
     * 秒数转换为 00:00:00格式的时间
     *
     * @param time
     * @return
     */
    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = "00:"+unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":"
                        + unitFormat(second);
            }
        }
        return timeStr;
    }

    /**
     * 秒数转换为00:00格式的时间
     *
     * @param time
     * @return
     */
    public static String secToTime_MS(int time) {
        String timeStr = null;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr =unitFormat(minute) + ":" + unitFormat(second);
            } else {

                if (minute > 59)
                    return "59:59";
                minute = minute % 60;
                second = time - minute * 60;
                timeStr = unitFormat(minute) + ":"
                        + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }

    /**
     * 00:00:00时间格式转换为秒数
     *
     * @param timeStr
     * @return
     */
    public static int timeToSec(String timeStr) {
        if (timeStr == null || "".equals(timeStr)) {
            Log.e(TAG, "timeToSec() error,timeStr is null or length==0");
            return 0;
        }
        String[] timeSec = timeStr.split(":"); // 标准的应该使用正则表达式验证输入的参数是否正确
        if (timeSec == null || timeSec.length != 3) {
            Log.e(TAG, "timeToSec() error,timeStr is not 00:00:00 format");
            return 0;
        }
        int hour = Integer.parseInt(timeSec[0]);
        int min = Integer.parseInt(timeSec[1]);
        int sec = Integer.parseInt(timeSec[2]);

        return hour * 3600 + min * 60 + sec;
    }

    /**
     * 秒数转换为 00:00格式的时间,时：分
     *
     * @param time
     * @return
     */
    public static String secToTimeWithoutSec(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        if (time <= 0)
            return "00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                timeStr = "00:"+unitFormat(minute);
            } else {
                hour = minute / 60;
                if (hour > 99)
                    return "99:59";
                minute = minute % 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute);
            }
        }
        return timeStr;
    }

    public static int calcalculateAge(String birth){
        if(birth.length()==4){  //只包含年份
            birth=birth+"-01-01";
        }
        SimpleDateFormat forma = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday=null;
        try {
            //将指定的字符串按日期格式化的格式转化为日期类型
            birthday = (Date) forma.parse(birth);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //获得1970-1-1到生日的毫秒数
        long bir = birthday.getTime();
        //获得1970-1-1到现在的毫秒数
        long now = System.currentTimeMillis();

        int age = (int)((now-bir)/1000/60/60/24/365);
        return age;

    }


    /*
     *根据年份计算年龄
     */
    public static int sampleCalculateAge(String birth){
        if(birth==null || birth.length()<4){
            return 0;
        }
        int age=0;
        Calendar a= Calendar.getInstance();
        if(birth.length()>4){
            birth=birth.substring(0, 4);
        }
        age=a.get(Calendar.YEAR)- Integer.parseInt(birth);
        return age;
    }

    /**
     * dp单位转换为px
     * @param context
     * @param value
     * @return
     */
    public static int dp2px(Context context, int value) {
        float v = context.getResources().getDisplayMetrics().density;
        return (int) (v * value + 0.5f);
    }
    public static int dp2px(Context context, float value) {
        float v = context.getResources().getDisplayMetrics().density;
        return (int) (v * value + 0.5f);
    }
    /**
     * sp单位转换为px
     * @param context
     * @param value
     * @return
     */
    public static int sp2px(Context context, int value) {
        float v = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (v * value + 0.5f);
    }
    public static int sp2px(Context context, float value) {
        float v = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (v * value + 0.5f);
    }

    public static float[] grouping(int[] rate, int age) {
        int z1 = (int) ((220 - age) * 0.5);
        int z2 = (int) ((220 - age) * 0.6);
        int z3 = (int) ((220 - age) * 0.7);
        int z4 = (int) ((220 - age) * 0.8);
        int z5 = (int) ((220 - age) * 0.9);
        int form0 = 0;
        int form1 = 0;
        int form2 = 0;
        int form3 = 0;
        int form4 = 0;
        int form5 = 0;
        int max, min;
        max = rate[0];
        min = rate[0];
        int len = rate.length;// 心跳个数
        float[] a = new float[13];
        for (int i = 0; i < len; i++) {
            Log.i("grouping", "rate[i]:" + rate[i]);
            if (rate[i] > max) {
                max = rate[i];
            } else if (rate[i] < min) {
                min = rate[i];
            }
            if (rate[i] < z1) {
                form0++;

                Log.i("grouping", "z0");
            } else if (z1 <= rate[i] && rate[i] < z2) {
                form1++;// z1区域点个数
                Log.i("grouping", "z1");
            } else if (z2 <= rate[i] && rate[i] < z3) {
                form2++;
                Log.i("grouping", "z2");
            } else if (z3 <= rate[i] && rate[i] < z4) {
                form3++;
                Log.i("grouping", "z3");
            } else if (z4 <= rate[i] && rate[i] < z5) {
                form4++;
                Log.i("grouping", "z4");
            } else if (z5 <= rate[i]) {
                form5++;
                Log.i("grouping", "z5");
            }

        }

        int acounnt = form1 + form2 + form3 + form4 + form5;
        a[0] = form0;
        if (acounnt != 0) {
            a[1] = (float) form1 / acounnt;
            a[2] = (float) form2 / acounnt;
            a[3] = (float) form3 / acounnt;
            a[4] = (float) form4 / acounnt;
            a[5] = (float) form5 / acounnt;
        } else {
            a[1] = (float) 0;
            a[2] = (float) 0;
            a[3] = (float) 0;
            a[4] = (float) 0;
            a[5] = (float) 0;
        }
        a[6] = max;
        a[7] = min;
        a[8] = (float) form1 / len;
        a[9] = (float) form2 / len;
        a[10] = (float) form3 / len;
        a[11] = (float) form4 / len;
        a[12] = (float) form5 / len;

        return a;

    }
	    /*
	     * 将距离转换为0.00
	     */

    public static BigDecimal formatDistance(Double dis){

        BigDecimal bd = new BigDecimal(String.valueOf(dis));
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd;

    }
	    /*
	     * 将小数保留小数点后n位
	     */

    public static float formatFloat(Float f, int digital){

        BigDecimal bd = new BigDecimal(String.valueOf(f));
        bd = bd.setScale(digital, BigDecimal.ROUND_HALF_UP);
        return bd.floatValue();

    }
     /*
	     * 将小数保留小数点后n位
	     */

    public static String formatFloatToString(Float f, int digital){

        BigDecimal bd = new BigDecimal(String.valueOf(f));
        bd = bd.setScale(digital, BigDecimal.ROUND_HALF_UP);
        return String.valueOf(bd.floatValue());

    }
    public  static Bitmap readBitMap(Context context, int resId){

        BitmapFactory.Options opt = new  BitmapFactory.Options();

        opt.inPreferredConfig =  Bitmap.Config.ARGB_8888;

        opt.inPurgeable = true;

        opt.inInputShareable = true;opt.inSampleSize=2;

        //  获取资源图片

        InputStream is =  context.getResources().openRawResource(resId);

        return  BitmapFactory.decodeStream(is, null, opt);

    }


    public static void stopService(Context context, Class<?> cls) {
        Log.e(TAG, "stopService");
        if (serviceHasRunning(context, cls.getName()))
            context.stopService(new Intent(context, cls));
    }
    /**
     * 获取所有运行中的服务
     *
     * @param context
     * @return
     */
    public static boolean serviceHasRunning(Context context,
                                            String serviceClassName) {
        if (serviceClassName == null)
            return false;
        // 得到ActivityManager
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Activity.ACTIVITY_SERVICE);

        List<ActivityManager.RunningServiceInfo> mRunningServiceInfo = mActivityManager
                .getRunningServices(100);
        // 循环查找任务名称
        for (ActivityManager.RunningServiceInfo info : mRunningServiceInfo)
            if (info.service != null
                    && serviceClassName.equals(info.service.getClassName()))
                return true;
        return false;
    }

    public static void showToast(Context context, String text, int duration) {
        if (mToast == null) {
            mToast = Toast.makeText(context, text, duration);
        } else {
            mToast.setText(text);
            mToast.setDuration(duration);
        }

        mToast.show();
    }

    public static void showToast(Context context, int resId, int duration) {
        String text = context.getResources().getString(resId);
        if (mToast == null) {
            mToast = Toast.makeText(context, text, duration);
        } else {
            mToast.setText(text);
            mToast.setDuration(duration);
        }

        mToast.show();
    }

    public static ArrayList<Integer> splitEcgData2List(String data) {
        if (data == null)
            return null;
        data = data.replaceAll("\r\n", ",");
        String[] dataArray = data.split(",");
        ArrayList<Integer> ecgMVDataList = null;
        if (dataArray.length > 0) {
            ecgMVDataList = new ArrayList<Integer>();
            for (String value : dataArray) {
                if (value.matches("[-]*[0-9]+")) {
                    ecgMVDataList.add(Integer.valueOf(value));
                }
            }
        }
        return ecgMVDataList;
    }

    /**
     * 得到两个时间之间的差值，注意时间的标准格式
     * @param timeBegin
     * @param timeEnd
     * @return
     */
    public static String getTimeBetweenValues(String timeBegin, String timeEnd){
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long between = 0;
        int sec;
        try {
            Date begin = dfs.parse(timeBegin);
            Date end = dfs.parse(timeEnd);
            between = (end.getTime() - begin.getTime());// 得到两者的毫秒数
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        sec=(int) (between/1000);
        return secToTime(sec);
    }

    public static String dealArray(double[] douArray){
        StringBuilder sbr=new StringBuilder();
        for(double dble:douArray){
            sbr.append(dble+"\n");
        }
        return sbr.toString();
    }


    public static String dealArray(float[] floatArray){
        StringBuilder sbr=new StringBuilder();
        for(float dble:floatArray){
            sbr.append(dble+"\n");
        }
        return sbr.toString();
    }



    /**
     * 判断网络是否连通
     *

     * @return
     */
    public static boolean isNetworkAvailable(Context context, boolean showToast) {
        boolean flag = isNetworkConnected(context);
        if (!flag && showToast) {
            showToast(context, R.string.tip_network_unavailable,
                    0);
        }
        return flag;
    }

    /**
     * @param context
     * @return 网络和云接口是否可用
     */

    public static boolean isNetworkAndServerAvailable(Context context) {
        return isNetworkAndServerAvailable(context, false, false);
    }

    public static boolean isNetworkAndServerAvailable(Context context,
                                                      boolean onlyCheckWifi, boolean showToast) {
        boolean flag = false;
        if (onlyCheckWifi) {
            flag = isWifiConnected(context);
        } else {
            flag = isNetworkConnected(context);
        }
			/*
			 * 暂不使用，减小服务器压力 if(flag){ try {
			 * MachTalkUtil.getWithThrowable(Const.MTALK_URL); } catch (Exception e)
			 * { e.printStackTrace(); flag = false; } }
			 */

        if (!flag && showToast) {
            showToast(context, R.string.tip_network_unavailable,
                    Toast.LENGTH_SHORT);
        }
        return flag;
    }

    // 判断网络是否可用
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    /**
     * 判断手机号码是否合理
     * @paramphoneNums
     */
    public static  boolean judgePhoneNums(Context context,String phoneNums) {
        if (isMatchLength(phoneNums, 11)
                && isMobileNO(phoneNums)) {
            return true;
        }
        CommUtil.showToast(context, "手机号码输入有误！", Toast.LENGTH_SHORT);
        return false;
    }
    /**
     * 判断一个字符串的位数
     * @return
     * @paramstr
     * @paramlength
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }
    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        /*
        * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
        * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
        * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
        */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

//    // 在数据备份网络选择设置条件下判断网络是否可用,选择移动网络下不备份数据时，只获取wifi状态是否可用
//    public static boolean isNetworkConnectedWithBackupSet(Context context) {
//        if (context != null) {
//            Map<String, Object> settings = new HashMap<String, Object>();
//            PreferencesService preferencesService = new PreferencesService(context);
//            settings = preferencesService.getPerferences();
//            boolean isautobackup = (Boolean) settings.get(Const.SETTINGS_BACKUP_KEY);
//            if(isautobackup){
//                return isNetworkConnected(context);
//            }else{
//                return isWifiConnected(context);
//            }
//
//        }
//        return false;
//    }

    // 判断WIFI网络是否可用
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isConnected();
            }
        }
        return false;
    }

    // 判断MOBILE网络是否可用
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isConnected();
            }
        }
        return false;
    }

    // 获取当前网络连接的类型信息
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }


    /**
     * 国内手机号码校验
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobilePhone(String mobiles) {
        Pattern p = Pattern.compile("^(1)\\d{10}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean isEmail(String email) {
        boolean b;
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        Pattern p = Pattern.compile(str);

        Matcher m = p.matcher(email);

        b= m.matches();

        return b;
    }

    public static String getTelephoneNumber(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String phone = tm.getLine1Number();
        if(phone !=null && phone.startsWith("+86")){
            phone = phone.replaceFirst("\\+86", "");
        }
        return 	phone;
    }

    public static String getRandomNum(int len) {
        if (len <= 0)
            return null;
        StringBuffer result = new StringBuffer();
        char number[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            result.append(number[random.nextInt(9)]);
        }
        return result.toString();
    }

    public final static String getMD52(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
     * 默认32位加密
     */
    public static String getMD5(String sourceStr) {
        return getMD5(sourceStr, true);
    }

    public static String getMD5(String sourceStr, boolean is32b) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            if (is32b) {
                result = buf.toString();// 32位的加密
            } else {
                result = buf.toString().substring(8, 24);// 16位的加密
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

//    public static String getEcgData(String familyId, String key) {
//        String fileName = createEcgFileName(familyId, key);
//        return FileTool.read(fileName, null,
//                FileTool.FILTER_TYPE_NOFILTER_ONELINE);
//    }
//
//    public static String createEcgFileName(String familyId, String index) {
//        return Const.SOFT_PATH + File.separator
//                + FileTool.modifyFileName(familyId + index) + ".txt";
//    }

    public static String getStrEnglish(int index) {
        if (index == 0) {
            return "A";
        } else if (index == 1) {
            return "B";
        } else if (index == 2) {
            return "C";
        } else if (index == 3) {
            return "D";
        } else if (index == 4) {
            return "F";
        } else if (index == 5) {
            return "G";
        } else if (index == 6) {
            return "H";
        } else if (index == 7) {
            return "I";
        } else if (index == 8) {
            return "J";
        } else if (index == 9) {
            return "K";
        } else if (index == 10) {
            return "L";
        } else if (index == 11) {
            return "M";
        } else if (index == 12) {
            return "N";
        } else if (index == 13) {
            return "O";
        } else if (index == 14) {
            return "P";
        } else if (index == 15) {
            return "Q";
        } else if (index == 16) {
            return "R";
        }
        return "Z";
    }

    public static String byteToBinary(byte bt){  //此方法仅适用于小于128的情况，java 返回的二进制为补码
        String ZERO="00000000";
        String s = Integer.toBinaryString(bt);
        if (s.length()>8) {
            return ZERO;
        } else if (s.length()< 8) {
            return ZERO.substring(s.length()) + s;
        }else{
            return s;
        }

    }

    public static String getNum(String str){
        String result=null;
        String regex = "\\d*";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);

        while (m.find()) {
            if (!"".equals(m.group()))
                result=m.group();
        }

        return result;
    }

    /**
     * 将方形头像转换成圆形
     *
     * @param bitmap
     *            传入Bitmap对象
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;

            left = 0;
            top = 0;
            right = width;
            bottom = width;

            height = width;

            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;

            float clip = (width - height) / 2;

            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;

            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right,
                (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top,
                (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);


        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);

        return output;
    }

    public static Bitmap createAvatar(String headUrl) {
        try {
            URL url = new URL(headUrl);
            InputStream in = url.openStream();
            Bitmap avatar = BitmapFactory.decodeStream(in);
            return avatar;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 日期比较，日期格式要求为“yyyy-MM-dd”，返回两者的相差天数
     * @param date1
     * @param date2
     * @return
     */
    public static int compareDates(String date1, String date2){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = sdf.parse(date1);
            Date dt2 = sdf.parse(date2);
            return (int) ((dt2.getTime()-dt1.getTime())/86400000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 描述：显示进度框.
     * @param context the context
     * @param indeterminateDrawable 用默认请写0

     */
    public static ProgressDialogFragment showProgressDialog(Context context, int indeterminateDrawable, int messageId) {
        FragmentActivity activity = (FragmentActivity)context;
        ProgressDialogFragment newFragment = ProgressDialogFragment.newInstance(indeterminateDrawable,context.getResources().getString(messageId));
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个系统转场动画
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }

    /**
     * 描述：移除Fragment.
     * @param context the context
     */
    public static void removeDialog(final Context context){
        new Handler().post(new Runnable() {

            @Override
            public void run() {
                try {
                    FragmentActivity activity = (FragmentActivity)context;
                    FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
                    // 指定一个系统转场动画
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                    Fragment prev = activity.getFragmentManager().findFragmentByTag(mDialogTag);
                    if (prev != null) {
                        ft.remove(prev);
                    }
                    ft.addToBackStack(null);
                    ft.commit();
                } catch (Exception e) {
                    //可能有Activity已经被销毁的异常
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 根据性别的值，返回对应字符串， 男 0   女 1
     * @param mContext
     * @param sex
     * @return
     */
    public static String sexToText(Context mContext, int sex){
        if(sex==0){
            return mContext.getResources().getString(R.string.male_simple);
        }else{
            return mContext.getResources().getString(R.string.female_simple);
        }

    }


    /**
     * 将时间格式yyyy/mm/dd hh:mm:ss字符串转换为时间 yyyy-MM-ddTHH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static String strToDateLong(String strDate) {
        String pat1 = "yyyy/MM/dd HH:mm:ss" ;
        SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ; // 实例化模板对象
        Date d = null ;
        try{
            d = sdf1.parse(strDate) ; // 将给定的字符串中的日期提取出来
        }catch(Exception e){ // 如果提供的字符串格式有错误，则进行异常处理
            e.printStackTrace() ; // 打印异常信息
        }
        SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "yyyy-MM-dd'T'HH:mm:ss");


        String dateString = dateFormatter.format(d);


        Log.e(TAG,"原："+strDate+",->:"+dateString);
        return dateString;
    }

    public static <T> void removeListDuplicate(List<T> duplicateList){
        Set<T> set = new HashSet<T>();
        List<T> newList=new ArrayList<T>();
        for (T hrd:duplicateList) {
            if (set.add(hrd))
                newList.add(hrd);
        }
        duplicateList.clear();
        duplicateList.addAll(newList);
    }

    public static String dealArrayEcg(int[] intArray){
        StringBuilder sbr=new StringBuilder();
        for(int dble:intArray){
            sbr.append(dble+" ");
        }
        sbr.append("\n");
        return sbr.toString();
    }
//    //Base64
//    public static String image2Base64(byte[] data) throws IOException {
//	        /*
//	         * Base64 encoder = new Base64(); data = encoder.encode(data);
//	         */
//        String content;
//        data = Base64.(data, false);;
//        StringBuffer sb = new StringBuffer();
//        for (byte bt : data) {
//            sb.append((char) bt);
//        }
//        content = sb.toString();
//        return sb.toString();
//    }

    /**
     * 获取指定文件大小
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFileSize(File file) throws Exception
    {
        long size = 0;
        if (file.exists()){
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        else{
            file.createNewFile();
            Log.e("获取文件大小","文件不存在!");
        }
        return size;
    }
    /**
     * 转换文件大小
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS)
    {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize="0B";
        if(fileS==0){
            return wrongSize;
        }
        if (fileS < 1024){
            fileSizeString = df.format((double) fileS) + "B";
        }
        else if (fileS < 1048576){
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        }
        else if (fileS < 1073741824){
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        }
        else{
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }
    public static boolean deleteFile(String SDPATH, String fileName) {
        //SDPATH目录路径，fileName文件名
        File file = new File(SDPATH + "/" + fileName);
        if (file == null || !file.exists() || file.isDirectory()){
            return false;
        }
        file.delete();

        return true;
    }


    public static boolean fileIsExists(File f){
        try{

            if(!f.exists()){
                return false;
            }

        }catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }
//    public static void call(Context context, String phone){
//        if(phone!=null&&phone.trim().length()>0){
//            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone.trim()));
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(intent);//调用上面这个intent实现拨号
//        }else{
//            // CommUtil.showToast(context, "电话号码不能为空", Toast.LENGTH_LONG);
//        }
//    }
//
//    // 屏幕解锁
//    public static void wakeUpAndUnlock(Context context) {
//        KeyguardManager km;
//        KeyguardManager.KeyguardLock kl;
//        PowerManager pm;
//        PowerManager.WakeLock wl;
//        //获取电源管理器对象
//        pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
//        //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
//        wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
//        //点亮屏幕
//        wl.acquire();
//        //得到键盘锁管理器对象
//        km= (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
//        kl = km.newKeyguardLock("unLock");
//        //解锁
//        kl.disableKeyguard();
//    }

    public static String dateAddSecond(String mDate, int mSecond) {
        SimpleDateFormat forma = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date birthday = null;
        try {
            // 将指定的字符串按日期格式化的格式转化为日期类型
            birthday = new Date(forma.parse(mDate).getTime() + mSecond * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return forma.format(birthday);
    }
    public static String ts2Time(long ts){
        Date d = new Date(ts*1000);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Log.e("Communtil","ts2Time：时间"+ sdf1.format(d));

        String tsStr;
        if(getStartTime()>(ts*1000)){
            Log.e("Communtil","ts2Time 不是当天：");
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd");
            tsStr = sdf.format(new Date(ts*1000));
        }else{
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            tsStr = sdf.format(new Date(ts*1000));
            tsStr=tsStr.substring(tsStr.length()-8,tsStr.length()-3);
            Log.e("Communtil","ts2Time 是当天："+tsStr);
        }
        return  tsStr;
    }
    public static Long getStartTime(){
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime();
    }

    private Long getEndTime(){
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime();
    }
    public  static Bitmap readBitMap2(Context context, int resId){

        BitmapFactory.Options opt = new  BitmapFactory.Options();

        opt.inPreferredConfig =  Bitmap.Config.ARGB_8888;

        opt.inPurgeable = true;

        opt.inInputShareable = true;opt.inSampleSize=2;

        //  获取资源图片

        InputStream is =  context.getResources().openRawResource(resId);

        return  BitmapFactory.decodeStream(is, null, opt);

    }
    public  static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }
    /*
    由文件uri获取绝对路径
     */
    public static String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

}

